package cn.com.winning.ecare.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.com.winning.ecare.common.CalendarDialog;
import cn.com.winning.ecare.common.Grideviewmenu;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.SlidingLayout;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**膳食
 * @author Administrator
 *
 */
public class SSSelect extends Activity {
	/** Called when the activity is first created. */

	private ViewPager viewPager;
	private List<View> views;
	private View view1, view2, view3;

	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int imageWidth;// 动画图片宽度
	private ImageView imageView;

	private TextView ssdate1,ssdate2,ssdate3, count1, count2, count3;// 获取需要查询的日期

	List<Map<String, Object>> list_m = new ArrayList<Map<String, Object>>();
	List<Map<String, Object>> list_mi = new ArrayList<Map<String, Object>>();
	List<Map<String, Object>> list_a = new ArrayList<Map<String, Object>>();

	CustomProgressDialog proDialog;// 加载框
	private SSSelect oThis = this;
	MyApplication myApp;
	private double count_m, count_mi, count_a;
	String dcdate;
	
	private ImageButton btnSearch;//日期选择按钮
	private LinearLayout layout;
	private int height, statusBarHeight;
	
	/**
	 * 侧滑布局对象，用于通过手指滑动将左侧的菜单布局进行显示或隐藏。
	 */
//	private SlidingLayout slidingLayout;
	
	private LinearLayout content;

	/**
	 * menu按钮，点击按钮展示左侧布局，再点击一次隐藏左侧布局。
	 */
	private ImageButton menuButton;
	
	private GridView gridView;
	Grideviewmenu gm;
	private TextView nametv,tv;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ssmain);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		myApp.getUserRecords().setUsername(myApp.getAccount());
		myApp.getUserRecords().setModule("SSSelect@膳食查询");
		UserRecord.getInstance(myApp.getUserRecords()).init();
		
		// 初始化view
		findView();
		//设置滑动菜单
		initSliding();
		// 设置监听
		setListener();


		// 设置点餐查询
		initImage();
		initTextView();
		initialSelect();

		// 获取当天数据
		getData();
		
		

	}
	private void initSliding(){
//		slidingLayout = (SlidingLayout) findViewById(R.id.slidingLayout);
		menuButton = (ImageButton) findViewById(R.id.menuButton);
//		content = (LinearLayout) findViewById(R.id.content);
		// 将监听滑动事件绑定在contentListView上
//		slidingLayout.setScrollEvent(content);
		menuButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				if (slidingLayout.isLeftLayoutVisible()) {
//					slidingLayout.scrollToRightLayout();
//				} else {
//					slidingLayout.scrollToLeftLayout();
//				}
				oThis.onBackPressed();
			}
		});
//		gm = new Grideviewmenu();
//		gridView = (GridView) findViewById(R.id.ssgridview_menu);
//		// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
//		SimpleAdapter adapter = new SimpleAdapter(this, getgvData(), // 数据来源
//				R.layout.grideview_menulist,// XML实现
//				new String[] { "ItemImage", "ItemText" }, // 动态数组与ImageItem对应的子项
//				new int[] { R.id.gridviewmenu_imageview, R.id.gridviewmenu_textview }// //ImageItem的XML文件里面的一个ImageView,两个TextView
//																				// ID
//		);
//		// 添加并且显示
//		gridView.setAdapter(adapter);
//		// 添加消息处理
//		gridView.setOnItemClickListener(clickListener);
//		nametv = (TextView)findViewById(R.id.ssusername_menu);
//		MyApplication myapp=(MyApplication)getApplication();
//		nametv.setText(myapp.getHzxm());
//		tv = (TextView)findViewById(R.id.ssout_menu);
//				
//		//滑动菜单里面退出按钮
//		tv.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				finish();
//				Intent intent = new Intent();
//				intent.setClass(oThis, Login.class);
//				startActivity(intent);
//			}
//		});
		
	}
	private void getData() {
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadFoodData()).start();
		list_m.clear();
		list_mi.clear();
		list_a.clear();

	}

	private void setListener() {
		btnSearch.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 初始化一个自定义的Dialog
				final CalendarDialog dialog = new CalendarDialog(
						SSSelect.this, R.style.MyDialog);
				// 获取状态栏高度
				Rect frame = new Rect();
				getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
				statusBarHeight = frame.top;
				Log.i("aaa", "statusBarHeight :" + statusBarHeight);
				// 获取layout高度
				height = layout.getHeight();
				dialog.show();
				Window mWindow = dialog.getWindow();
				WindowManager windowManager = getWindowManager();
				Display display = windowManager.getDefaultDisplay();
				WindowManager.LayoutParams lp = mWindow.getAttributes();
				lp.x = 0;
				lp.y = height + statusBarHeight;
				lp.width = (int) (display.getWidth()); // 设置宽度
				lp.height = (int) (display.getHeight()) - height
						- statusBarHeight;// 设置高度
				mWindow.setAttributes(lp);

				Button btnok = (Button) dialog.findViewById(R.id.btnok);
				Button btncancel = (Button) dialog.findViewById(R.id.btncancel);

				btnok.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						TextView tvSelected = (TextView) dialog
								.findViewById(R.id.tvSelected);
						String str = tvSelected.getText().toString();
						String[] strs = tvSelected.getText().toString()
								.split(":");
						if (strs.length >= 2) {
							dcdate = strs[1];
						}
						
						dialog.dismiss();
						proDialog = CustomProgressDialog.createDialog(oThis);
						proDialog.setMessage("数据加载中...");
						proDialog.show();
						proDialog.setCanceledOnTouchOutside(false);
						// 这里单开一个线程和后台数据交互
						new Thread(new LoadFoodData()).start();
						list_m.clear();
						list_mi.clear();
						list_a.clear();
						count_m = 0;
						count_mi = 0;
						count_a = 0;
						initialSelect();
					}
				});

				btncancel.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});

			}
		});
	

	}

	private void findView() {
		btnSearch = (ImageButton) this.findViewById(R.id.searchButton);
		layout = (LinearLayout) this.findViewById(R.id.sslayout);
		Date now = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dcdate = simpleDateFormat.format(now);//默认当天
	}

	private void initFoodDate() {
		try {
			Message msg = myHandler.obtainMessage();
			Bundle bundle = new Bundle();
				List<NameValuePair> ls = new ArrayList<NameValuePair>();
				ls.add(new BasicNameValuePair("userid", myApp.getAccount()));
				ls.add(new BasicNameValuePair("sfzh",myApp.getSfzh()));
				ls.add(new BasicNameValuePair("cpdate", dcdate
						.replace("-", "").replace("-", "")));
				JSONObject json = HTTPGetTool.getTool().post(
						URLUtils.HOST + URLUtils.URLFOOD, ls);
				Map<String, Object> map;
				if (json != null) {
					if (!json.toString().equals(
							"{\"msg\":\"系统错误！\",\"success\":\"false\"}")) {
						if (!json.getString("blinfo").equals("[]")) {
							JSONArray jsonArr = json.getJSONArray("blinfo");
							JSONObject js = null;
							for (int i = 0; i < jsonArr.length(); i++) {
								map = new HashMap<String, Object>();
								js = jsonArr.getJSONObject(i);
								String temp = js.getString("cplb");
								if (temp.equals("早")) {
									map.put("cpname", js.getString("cpname"));
									map.put("cpsl", "X"+js.getString("cpsl")+js.getString("cpdw"));
									map.put("cpdj", js.getString("cpdj"));
									count_m += Double.parseDouble(js.getString("cpje"));
									list_m.add(map);
								} else if (temp.equals("中")) {
									map.put("cpname", js.getString("cpname"));
									map.put("cpsl", "X"+js.getString("cpsl")+js.getString("cpdw"));
									map.put("cpdj", js.getString("cpdj"));
									count_mi += Double.parseDouble(js.getString("cpje"));
									list_mi.add(map);
								} else {
									map.put("cpname", js.getString("cpname"));
									map.put("cpsl", "X"+js.getString("cpsl")+js.getString("cpdw"));
									map.put("cpdj", js.getString("cpdj"));
									count_a += Double.parseDouble(js.getString("cpje"));
									list_a.add(map);
								}
	
							}
							bundle.putInt("type", 0);
							bundle.putString("msg", "");
						} else {
							bundle.putInt("type", -1);
							bundle.putString("msg", "暂无数据");
						}
					} else {
						bundle.putInt("type", -1);
						bundle.putString("msg", "系统错误");
					}
				} else {
					bundle.putInt("type", -1);
					bundle.putString("msg", "网络连接失败!");
				}

			msg.setData(bundle);
			myHandler.sendMessage(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class LoadFoodData implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Looper.prepare();
			initFoodDate();
			Looper.loop();

		}

	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			int type = msg.getData().getInt("type");
			switch (type) {
			case -1:
				proDialog.dismiss();
				Toast.makeText(oThis, msg.getData().getString("msg"),
						Toast.LENGTH_SHORT).show();
				break;
			case 0:
				proDialog.dismiss();
				setData();
				break;

			default:
				break;
			}
		};
	};

	private void setData() {
		// 设置早餐
		ListView lv_breakfast = (ListView) view1.findViewById(R.id.listView1);
		// 设置午餐
		ListView lv_lunch = (ListView) view2.findViewById(R.id.listView1);
		// 设置晚餐
		ListView lv_dinner = (ListView) view3.findViewById(R.id.listView1);
		
		lv_breakfast.setAdapter(new SimpleAdapter(SSSelect.this, list_m,
				R.layout.ssbreakfast_item, new String[] { "cpname", "cpsl",
						"cpdj" }, new int[] { R.id.brecp, R.id.bresl,
						 R.id.bredj }));
		lv_lunch.setAdapter(new SimpleAdapter(SSSelect.this, list_mi,
				R.layout.ssbreakfast_item, new String[] { "cpname", "cpsl",
						"cpdj" }, new int[] { R.id.brecp, R.id.bresl,
						R.id.bredj }));
		lv_dinner.setAdapter(new SimpleAdapter(SSSelect.this, list_a,
				R.layout.ssbreakfast_item, new String[] { "cpname", "cpsl",
						"cpdj" }, new int[] { R.id.brecp, R.id.bresl,
						R.id.bredj }));
		count1.setText("小计：" + count_m + " 元");
		count2.setText("小计：" + count_mi + " 元");
		count3.setText("小计：" + count_a + " 元");
		ssdate1.setText(dcdate);
		ssdate2.setText(dcdate);
		ssdate3.setText(dcdate);
		
	}

	private class MyListViewDapter extends BaseAdapter {

		public int getCount() {
			// TODO Auto-generated method stub
			return 0;
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			return null;
		}

	}

	private void initTextView() {
		// TODO Auto-generated method stub
		TextView textView1 = (TextView) findViewById(R.id.breakfast_tv);
		TextView textView2 = (TextView) findViewById(R.id.lunch_tv);
		TextView textView3 = (TextView) findViewById(R.id.dinner_tv);

		textView1.setOnClickListener(new MyOnClickListener(0));
		textView2.setOnClickListener(new MyOnClickListener(1));
		textView3.setOnClickListener(new MyOnClickListener(2));
	}

	private class MyOnClickListener implements OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		public void onClick(View v) {
			viewPager.setCurrentItem(index);
		}

	}

	private void initImage() {
		// TODO Auto-generated method stub
		imageView = (ImageView) findViewById(R.id.iv_bottom_line);
		imageWidth = imageView.getLayoutParams().width;// 获取图片宽度
		Log.i("aaa", "imageWidth:" + imageWidth);
		DisplayMetrics dm = new DisplayMetrics();

		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		Log.i("aaa", "screenW:" + screenW);
		offset = (screenW / 3 - imageWidth) / 2;// 计算偏移量
		Log.i("aaa", "offset:" + offset);
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		imageView.setImageMatrix(matrix);// 设置动画初始位置

	}

	private void initialSelect() {
		// TODO Auto-generated method stub
		viewPager = (ViewPager) this.findViewById(R.id.viewPager2);
		views = new ArrayList<View>();
		LayoutInflater inflater1 = LayoutInflater.from(this);
		view1 = (View) inflater1.inflate(R.layout.ssbreakfast, null);
		view2 = (View) inflater1.inflate(R.layout.ssbreakfast, null);
		view3 = (View) inflater1.inflate(R.layout.ssbreakfast, null);
		count1 = (TextView) view1.findViewById(R.id.count);
		count2 = (TextView) view2.findViewById(R.id.count);
		count3 = (TextView) view3.findViewById(R.id.count);
		ssdate1 = (TextView) view1.findViewById(R.id.sstime);
		ssdate2 = (TextView) view2.findViewById(R.id.sstime);
		ssdate3 = (TextView) view3.findViewById(R.id.sstime);
		views.add(view1);
		views.add(view2);
		views.add(view3);
		viewPager.setAdapter(new MyViewPagerAdaper(views));
		viewPager.setCurrentItem(0);
		viewPager.setOnPageChangeListener(new MyOnPagerChangeListener());
	}

	class MyOnPagerChangeListener implements ViewPager.OnPageChangeListener {

		int one = offset * 2 + imageWidth;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量

		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			Animation animation = new TranslateAnimation(one * currIndex, one
					* arg0, 0, 0);// 显然这个比较简洁，只有一行代码。
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			imageView.startAnimation(animation);
			
		}

	}

	class MyViewPagerAdaper extends PagerAdapter {
		private List<View> mListViews;

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			container.removeView(mListViews.get(position));
		}

		@Override
		public int getItemPosition(Object object) {
			// TODO Auto-generated method stub
			return super.getItemPosition(object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			// TODO Auto-generated method stub
			container.addView(mListViews.get(position));
			return mListViews.get(position);
		}

		public MyViewPagerAdaper(List<View> mListViews) {
			super();
			this.mListViews = mListViews;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mListViews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public void startUpdate(ViewGroup container) {
			// TODO Auto-generated method stub
			super.startUpdate(container);
		}

	}
	 // 获取GrideView数据
//	private ArrayList<HashMap<String, Object>> getgvData() {
//		MyApplication myApplication = (MyApplication) getApplication();
//		return gm.initItem(myApplication);//初始化GrideView
//	}
// // 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
//	private OnItemClickListener clickListener = new OnItemClickListener() {
//
//		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//				long arg3) {
//			if (slidingLayout.isLeftLayoutVisible()) {//如果滑动菜单隐藏，屏蔽点击事件
//			Intent intent = null;
//			HashMap<String, Object> Item = (HashMap<String, Object>) arg0
//					.getItemAtPosition(arg2);
//			intent = gm.findActivity(intent,Item, oThis);
//			startActivity(intent);
//			oThis.finish();
//			}
//		}
//	};
}
